package com.ljf.servlet.repeatable;

import com.ljf.framework.context.LjfContextManager;
import com.ljf.framework.filter.LjfAbstractFilter;
import com.ljf.framework.log.LjfLogManager;
import com.ljf.framework.log.LjfLogService;
import com.ljf.framework.util.LjfStringUtil;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 拦截请求，注入RepeatedlyRequestWrapper定义类，实现可重复读取inputStream的request
 * Repeatable 过滤器
 */
public class RepeatableFilter extends LjfAbstractFilter {

    LjfLogService logger = LjfLogManager.getLogger(RepeatableFilter.class);

    @Override
    public boolean doCusFilter() {
        return true;
    }

    public ServletRequest doCusFilter(ServletRequest request) {
        if (!"POST".equals(LjfContextManager.getRequest().getMethod())){
            return request;
        }
        logger.info("RepeatableFilter init success");

        ServletResponse response = (ServletResponse) LjfContextManager.getResponse().getSource();
        if (request instanceof HttpServletRequest
                && LjfStringUtil.startsWithIgnoreCase(request.getContentType(),"application/json")) {
            try {
                request = new RepeatedlyRequestWrapper((HttpServletRequest) request, response);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != request) {
            LjfContextManager.setRequest(request);
            return request;
        }
        return request;
    }

    @Override
    public Integer getOrder() {
        return 10;
    }
}
